package net.esj.basic.config;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.esj.basic.utils.GetClassLoader;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;

public class MObjectConfig {
	
	private static final Map<String,MConfig> mobjectCache = new HashMap<String, MConfig>();
	
	private static boolean reload = false;
	
	private static final String MOBJECT_XML_FILE = "mobject.xml";
	
	public static MConfig getConfig(String key){
		if(!reload){
			load();
			reload = true;
		}
		return mobjectCache.get(key.toLowerCase());
	}
	
	public static List<MConfig> getConfigs(String... keys){
		if(!reload){
			load();
			reload = true;
		}
		List<MConfig> list = new ArrayList<MObjectConfig.MConfig>();
		for(String k : keys){
			MConfig mc = getConfig(k);
			if(mc!=null){
				list.add(mc);
			}
		}
		return list;
	}
	
	public static void reload(){
		reload = false;
	}
	
	public static void load() {
		URL url = GetClassLoader.fromContext().getResource(MOBJECT_XML_FILE);
		File file = new File(url.getPath());
		SAXReader reader = new SAXReader();

		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("UTF-8");

		if (file.exists()) {
			Document document;
			try {
				document = reader.read(file);
				Element root = document.getRootElement();
				
				for (Iterator i = root.elementIterator("mobject"); i.hasNext();) {
					Element mobject= (Element) i.next();
					Element mtype = mobject.element("mtype");
					Element uri = mobject.element("uri");
					Element name = mobject.element("name");
					MConfig mc = new MConfig();
					mc.setMtype(mtype.getTextTrim().toLowerCase());
					mc.setName(name.getTextTrim());
					mc.setUri(uri.getTextTrim());
					mobjectCache.put(mc.getMtype(), mc);
				}
			} catch (DocumentException e) {
				e.printStackTrace();
			}

		}
	}

	public static final class MConfig{
		private String name;
		private String mtype;
		private String uri;
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getMtype() {
			return mtype;
		}
		public void setMtype(String mtype) {
			this.mtype = mtype;
		}
		public String getUri() {
			return uri;
		}
		public void setUri(String uri) {
			this.uri = uri;
		}
		
	}
}
